import { useEffect, useRef, forwardRef, useImperativeHandle } from "react";
import "./EarthPiece.css";
import { PatrolDetectionPoint } from "../api/gis";
import { EarthPieceRenderer } from "./EarthPieceRenderer";
import { LatLngRect } from "../utils/earthUtils";

interface EarthPieceProps {
  detectionPoints: PatrolDetectionPoint[];
  tileUrlTemplate: string;
  maxLevel?: number;
  // 巡视区的经纬度范围
  latLngBounds?: {
    minLat: number;
    maxLat: number;
    minLng: number;
    maxLng: number;
  };
  onCoordinateClick?: (coord: { lat: number; lng: number } | null) => void;
  onCoordinateHover?: (coord: { lat: number; lng: number } | null) => void;
  onDetectionPointClick?: (detectionPoint: PatrolDetectionPoint | null) => void;
  onDetectionPointHover?: (detectionPoint: PatrolDetectionPoint | null) => void;
  onSelectionEnd?: (selectionRect: LatLngRect, intersectingDetectionPoints: PatrolDetectionPoint[]) => void;
  simulatedMetaKey?: boolean;
}

export interface EarthPieceRef {
  zoomIn: () => void;
  zoomOut: () => void;
  resetView: () => void;
  getSelectedPoints: () => PatrolDetectionPoint[];
  clearSelection: () => void;
}

const EarthPiece = forwardRef<EarthPieceRef, EarthPieceProps>(
  (
    {
      detectionPoints,
      tileUrlTemplate,
      maxLevel = 5,
      latLngBounds,
      onCoordinateClick,
      onCoordinateHover,
      onDetectionPointClick,
      onDetectionPointHover,
      onSelectionEnd,
      simulatedMetaKey = false,
    },
    ref
  ) => {
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const rendererRef = useRef<EarthPieceRenderer | null>(null);

    // 初始化渲染器
    useEffect(() => {
      const canvas = canvasRef.current;
      if (!canvas) return;

      const renderer = new EarthPieceRenderer(canvas, {
        tileUrlTemplate,
        maxLevel,
        latLngBounds,
        simulatedMetaKey,
        onCoordinateClick,
        onCoordinateHover,
        onDetectionPointClick,
        onDetectionPointHover,
        onSelectionEnd,
      });

      rendererRef.current = renderer;

      return () => {
        renderer.destroy();
      };
    }, []); // 只在组件挂载时初始化一次

    // 更新瓦片URL模板
    useEffect(() => {
      if (rendererRef.current) {
        rendererRef.current.updateTileUrlTemplate(tileUrlTemplate);
      }
    }, [tileUrlTemplate]);

    // 更新经纬度范围
    useEffect(() => {
      if (rendererRef.current && latLngBounds) {
        rendererRef.current.updateLatLngBounds(latLngBounds);
      }
    }, [latLngBounds]);

    // 更新探测点数据
    useEffect(() => {
      if (rendererRef.current) {
        rendererRef.current.setData(detectionPoints);
      }
    }, [detectionPoints]);

    // 更新模拟Meta键状态
    useEffect(() => {
      if (rendererRef.current) {
        rendererRef.current.updateSimulatedMetaKey(simulatedMetaKey);
      }
    }, [simulatedMetaKey]);

    // 暴露控制方法
    useImperativeHandle(ref, () => ({
      zoomIn: () => {
        rendererRef.current?.zoomIn();
      },
      zoomOut: () => {
        rendererRef.current?.zoomOut();
      },
      resetView: () => {
        rendererRef.current?.resetView();
      },
      getSelectedPoints: () => {
        return rendererRef.current?.getSelectedPoints() || [];
      },
      clearSelection: () => {
        rendererRef.current?.clearSelection();
      },
    }));

    return (
      <div className="earth-piece-container">
        <canvas 
          ref={canvasRef} 
          className="earth-piece-canvas"
          style={{
            cursor: simulatedMetaKey ? "crosshair" : "grab"
          }}
        />
      </div>
    );
  }
);

EarthPiece.displayName = "EarthPiece";

export default EarthPiece;
